<?php

namespace Wgx\PdoEx;


final class QueryBuilderResult
{
    /** @var \PDO */
    private $pdo;
    /** @var string */
    private $sql;
    /** @var array|null */
    private $sqlParams;

    private $isExecuted;

    /** @var bool */
    private $isOk;
    /** @var null|\PDOStatement */
    private $pdoStatement;

    /**
     * QueryBuilderResult constructor.
     * @param \PDO $pdo
     * @param string $sql
     * @param array|null $sqlParams
     */
    public function __construct(\PDO $pdo, $sql, $sqlParams = null)
    {
        $this->pdo = $pdo;
        $this->sql = $sql;
        $this->sqlParams = $sqlParams;

        $this->isExecuted = false;
        $this->isOk = false;
    }

    /**
     * @return \PDO
     */
    public function getPdo()
    {
        return $this->pdo;
    }

    /**
     * @return string
     */
    public function getSql()
    {
        return $this->sql;
    }

    /**
     * @return array|null
     */
    public function getSqlParams()
    {
        return $this->sqlParams;
    }

    /**
     * @return boolean
     */
    public function getIsOk()
    {
        if (!$this->isExecuted) {
            $this->execute();
        }

        return $this->isOk;
    }

    /**
     * @return null|\PDOStatement
     */
    public function getPdoStatement()
    {
        if (!$this->isExecuted) {
            $this->execute();
        }

        return $this->pdoStatement;
    }

    /**
     * @return $this
     */
    public function execute()
    {
        if ($this->isExecuted) {
            return $this;
        }
        $this->isExecuted = true;

        if ($this->sql) {
            $this->pdoStatement = $this->pdo->prepare($this->sql);
            $this->isOk = $this->pdoStatement->execute($this->sqlParams);
        }

        return $this;
    }
}